package com.yaoweigroup.community.ui.bm;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.entity.StringEntity;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.renderscript.Type;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ProgressBar;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.DbException;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.yaoweigroup.community.R;
import com.yaoweigroup.community.adapter.BMGridAdapter;
import com.yaoweigroup.community.config.Urls;
import com.yaoweigroup.community.db.DBUtil;
import com.yaoweigroup.community.enity.TypeIcon;
import com.yaoweigroup.community.util.JsonUtil;
import com.yaoweigroup.community.util.LogUtil;
import com.yaoweigroup.community.util.UtilHttp;

/**
 * 便民服务 主页
 * 
 * @author xi
 * 
 */
public class BMHomeActivity extends Activity {

	private GridView gridView;
	private BMGridAdapter gridAdapter;
	private List<TypeIcon> list;
	private ObjectMapper mapper;
	private DBUtil dbUtil;
	private ProgressBar progress;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mapper = new ObjectMapper();
		dbUtil = DBUtil.newInstance(this);
		setContentView(R.layout.activity_bm_home);
		initRes();

	}

	@Override
	protected void onResume() {
		super.onResume();
		try {
			list = dbUtil.db.findAll(TypeIcon.class);
			if (list != null && list.size() > 0) {
				gridAdapter.setDataChange(list);
			} else {
				obtainData();
			}
		} catch (DbException e) {
			LogUtil.e("wxf", "DB=" + e.toString());
		}
	}

	private void initRes() {
		list = new ArrayList<TypeIcon>();
		progress = (ProgressBar) findViewById(R.id.progress);
		gridView = (GridView) findViewById(R.id.gridView);
		gridAdapter = new BMGridAdapter(this, list);
		gridView.setAdapter(gridAdapter);

		gridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {

				Intent intent = new Intent(BMHomeActivity.this,
						NearListActivity.class);
				intent.putExtra("type", list.get(position));
				startActivity(intent);

			}
		});
	}

	/**
	 * 获取类别
	 */
	private void obtainData() {
		progress.setVisibility(View.VISIBLE);
		HttpUtils http = UtilHttp.getHttpUtils(this);
		RequestParams params = new RequestParams();
		JsonUtil jsonUtil = new JsonUtil();
		LogUtil.d("wxf", jsonUtil.toString());
		StringEntity enity = null;
		try {
			enity = new StringEntity(jsonUtil.toString());
		} catch (Exception e) {
			LogUtil.e("wxf", e.toString());
		}
		params.setContentType("application/json");
		params.setBodyEntity(enity);
		params.setHeader("Accept", "application/json");
		http.send(HttpRequest.HttpMethod.POST, Urls.getServerType, params,
				new RequestCallBack<String>() {

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						LogUtil.d("wxf", "result = " + responseInfo.result);
						String result = responseInfo.result;
						try {
							JSONObject obj = new JSONObject(result);
							int state = obj.getInt("state");
							String data = obj.getString("data");
							if (state == 200) {
								list = mapper.readValue(data,
										new TypeReference<List<TypeIcon>>() {
										});
								handler.sendEmptyMessage(OBTAIN_SUCCESS);
							} else {
								handler.sendEmptyMessage(OBTAIN_FAIL);

							}
						} catch (Exception e) {
							handler.sendEmptyMessage(OBTAIN_FAIL);

							LogUtil.e("wxf", e.toString());
						}

					}

					@Override
					public void onFailure(HttpException error, String msg) {
						LogUtil.e("wxf", error.toString());
						handler.sendEmptyMessage(OBTAIN_FAIL);

					}

				});
	}

	public final int OBTAIN_SUCCESS = 0x2210;
	public final int OBTAIN_FAIL = OBTAIN_SUCCESS + 1;
	Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			progress.setVisibility(View.GONE);
			switch (msg.what) {
			case OBTAIN_SUCCESS:
				if (list != null && list.size() > 0) {
					gridAdapter.setDataChange(list);
					for (int i = 0; i < list.size(); i++) {
						list.get(i).setSort(i);
					}
					try {
						dbUtil.db.saveOrUpdateAll(list);
					} catch (DbException e) {
						LogUtil.e("wxf", "dbException =" + e.toString());
					}
				}
				break;
			case OBTAIN_FAIL:

				break;
			}
		};
	};

	private long firstTime = 0;

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			long secondTime = System.currentTimeMillis();
			if (secondTime - firstTime > 2000) { // 如果两次按键时间间隔大于2秒，则不退出
				Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
				firstTime = secondTime;// 更新firstTime
				return true;
			} else { // 两次按键小于2秒时，退出应用
				System.exit(0);
			}
		}
		return super.onKeyDown(keyCode, event);
	}

}
